package com.inspur.resourcequery;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.inspur.common.BaseActivity;
import com.inspur.common.MyApplication;
import com.inspur.common.domain.RequestInfo;
import com.inspur.common.utils.URLManager;
import com.inspur.resourcequery.adapter.ResDetailPagerAdapter;
import com.inspur.resourcequery.model.ResAttr;
import com.inspur.resourcequery.model.ResData;
import com.inspur.resourcequery.model.ResRelationData;
import com.wewin.stategrid.print.Print;

public class ResDetailActivity extends BaseActivity {

	private ResData models;

	private String code;
	public List<ResAttr> resAttributeList = new ArrayList<ResAttr>();
	public List<ResRelationData> resRelationList = new ArrayList<ResRelationData>();
	
	private String resClassName;
	private String intId;
	
	private ViewPager mViewPager;
	private MyApplication application;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_resdetail);
		application = (MyApplication)this.getApplication();
		
		if(this.getIntent().getExtras().containsKey("code")){
			code = this.getIntent().getStringExtra("code");
		} else if(this.getIntent().getExtras().containsKey("resClassName")){
			resClassName = this.getIntent().getStringExtra("resClassName");
			intId = this.getIntent().getStringExtra("intId");
		} else {
			models = (ResData) getIntent().getSerializableExtra("data");
		}
		
		if(this.getIntent().getStringExtra("serveraddress") != null){
			URLManager.URL = this.getIntent().getStringExtra("serveraddress");
		}
		
		actionBar.setTitle("资源详情");
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		queryDetailData();

	}

	/**
	 * 查询数据列表
	 */
	protected void queryDetailData() {
		RequestInfo req = new RequestInfo();
		req.context = ResDetailActivity.this;
		req.requestUrl = URLManager.URL + URLManager.RES_QUERYATTROBJECT_BYID;
		try {
			JSONObject condition = new JSONObject();
			if(models != null){
				condition.put("ResClassName", models.getResclassenname());
				condition.put("int_id", models.getInt_id());
			} else if(code != null){
				condition.put("code", code);
			} else {
				condition.put("ResClassName", resClassName);
				condition.put("int_id", intId);
			}
			req.params = condition.toString();
			Log.e("requestUrl", req.requestUrl);
			Log.e("param", req.params);
			// req.params="?"+condition.toString();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		super.getDataFromServer(req, new DataCallback<String>() {
			@Override
			public void processData(String paramObject) {
				Log.d("paramObject:", paramObject);
				proccessDetailData(paramObject);
			}

			@Override
			public void getDataFailed() {
				// 这里仅作演示，实际请求失败后怎么操作根据实际情况来看

			}

		}, ResDetailActivity.this);
	}

	public void proccessDetailData(String paramObject) {
		
		try {
			JSONObject jsonObj = new JSONObject(paramObject);
			String message = "";
			if (jsonObj.has("message"))
				message = jsonObj.getString("message") + "";
			if (!message.equals("")) {
				Toast.makeText(ResDetailActivity.this, "加载数据出错:" + message, Toast.LENGTH_SHORT).show();
			}
			if("-1".equals(jsonObj.getString("resClassName"))){
				Toast.makeText(ResDetailActivity.this, "二维码信息错误！", Toast.LENGTH_SHORT).show();
			} else {
				
				String name = "";
				resAttributeList = new ArrayList<ResAttr>();
				JSONArray jsonArray = jsonObj.getJSONArray("attrList");
				for(int i = 0; i < jsonArray.length(); i++){
					JSONObject attrObj = jsonArray.getJSONObject(i);
					ResAttr attribute = new ResAttr();
					attribute.setAttributeCnName(attrObj.getString("attributeCnName"));
					attribute.setAttributeEnName(attrObj.getString("attributeEnName"));
					if(attrObj.get("attributeTransValue") ==  null || "null".equalsIgnoreCase(attrObj.getString("attributeTransValue"))){
						attribute.setAttributeTransValue("");
						attribute.setAttributeValue("");
					} else {
						attribute.setAttributeTransValue(attrObj.getString("attributeTransValue"));
						attribute.setAttributeValue(attrObj.getString("attributeValue"));
					}
					attribute.setDataLength(attrObj.getInt("dataLength"));
					attribute.setDataType(attrObj.getString("dataType"));
					attribute.setIfChange(attrObj.getInt("ifChange"));
					attribute.setIfModify(attrObj.getInt("ifModify"));
					attribute.setInputType(attrObj.getString("inputType"));
					attribute.setParentColumn(attrObj.getString("parentColumn"));
					
					if(attribute.getAttributeEnName().equalsIgnoreCase("zh_label")){
						name = attribute.getAttributeTransValue();
					}
					resAttributeList.add(attribute);
				}
				
				JSONArray resultList = jsonObj.getJSONArray("relationList");
				if (resultList != null && resultList.length() > 0) {
					for (int i = 0; i < resultList.length(); i++) {
						JSONObject obj = resultList.getJSONObject(i);
						ResRelationData data = new ResRelationData();
						data.setRelationid(obj.getString("relationid"));
						data.setShowvalue(obj.getString("showvalue"));
						data.setRelated_attr(obj.getString("related_attr"));
						data.setName(obj.getString("name"));
						data.setRelated_class(obj.getString("related_class"));
						data.setType(obj.getString("type"));
						data.setAttr_value(obj.getString("attr_value"));
						resRelationList.add(data);
					}
				}
				
				if(models == null){
					models = new ResData();
					models.setName(name);
					models.setResclassenname(jsonObj.getString("resClassName"));
					models.setInt_id(jsonObj.getString("intId"));
				} 
				models.setDimcode(jsonObj.getString("dimcode"));
				models.setDimcodeField(jsonObj.getString("dimcodeField"));
				models.setDimcodeFlag(jsonObj.getString("dimcodeFlag"));
				models.setDimcodeHint(jsonObj.getString("dimcodeHint"));
				initTab();
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private final TabListener mTabListener = new TabListener() {
		private final static String TAG = "TabListener";

		@Override
		public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
			// TODO Auto-generated method stub
			Log.d(TAG, "onTabReselected");
		}

		@Override
		public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
			// TODO Auto-generated method stub
			Log.d(TAG, "onTabSelected()");
			if (mViewPager != null)
				mViewPager.setCurrentItem(tab.getPosition());
		}

		@Override
		public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
			// TODO Auto-generated method stub
			Log.d(TAG, "onTabUnselected()");
		}
	};

	class PagerChangeListener implements OnPageChangeListener {
		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onPageSelected(int arg0) {
			getActionBar().selectTab(getActionBar().getTabAt(arg0));
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.detail, menu);
		return true;
	}
	
	public boolean onPrepareOptionsMenu(Menu menu) {
	     super.onPrepareOptionsMenu(menu);
	     if(models != null && ("0".equals(models.getDimcodeFlag()) || ("".equals(models.getDimcode()) && "0".equals(models.getDimcodeHint())))){
	    	 menu.removeItem(R.id.menu_code_print);
	     }
	     return true;
	  }

	protected void initTab() {
		actionBar.addTab(actionBar.newTab().setText("资源详情").setTabListener(mTabListener));
		actionBar.addTab(actionBar.newTab().setText("关联资源").setTabListener(mTabListener));

		mViewPager = (ViewPager) findViewById(R.id.vPager);
		getFragmentManager();
		mViewPager.setAdapter(new ResDetailPagerAdapter(
				getSupportFragmentManager()));
		mViewPager.setOnPageChangeListener(new PagerChangeListener());
		mViewPager.setCurrentItem(0);
	}

	//菜单-物理信息
	private static final int MENU_PHYSICAL = 100;
	//菜单-GIS定位
	private static final int MENU_GIS = 200;
	//菜单-经纬度较准
	private static final int MENU_POSITION = 300;
	//菜单-错误上报
	private static final int MENU_ERROR_REPORT= 400;
	//菜单-二维码打印
	private static final int MENU_CODE_PRINT= 500;
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		
		Intent intent;
		Bundle bundle = new Bundle();
		
		// TODO Auto-generated method stub
		switch (item.getOrder()) {
		case 0:
			super.onBackPressed();   
			break;
		case MENU_PHYSICAL:
			intent = new Intent(ResDetailActivity.this, PhysicsInfoActivity.class);   
			bundle.putSerializable("data", models);
			intent.putExtras(bundle);
			this.startActivity(intent);
			break;
		case MENU_GIS:
				trans2Gis(0);
			break;
		case MENU_POSITION:
				trans2Gis(1);
			break;
		case MENU_ERROR_REPORT:
			intent = new Intent(ResDetailActivity.this, ErrorReportActivity.class);   
			bundle.putSerializable("data", models);
			intent.putExtras(bundle);
			this.startActivity(intent);
			break;
		case MENU_CODE_PRINT:
			if(models.getDimcode() == null || "".equals(models.getDimcode())){
//				if(false){
				Toast.makeText(getApplicationContext(), models.getDimcodeHint(), Toast.LENGTH_SHORT).show();
				
			} else {
				PackageInfo packageInfo;
				try {
					packageInfo = this.getPackageManager().getPackageInfo("com.inspur.codeprint", 0);
				} catch (NameNotFoundException e) {
					packageInfo = null;
				}
				if(packageInfo == null){
					
					Print p = new Print();
					String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
							"<Data><Print>" +
							"<PrintType>粘贴式设备</PrintType>" +
							"<Code>" + models.getDimcode() + "</Code>" +
							"<Text>"+models.getName()+"</Text>" +
							"<Model>"+models.getResclassenname()+"</Model>" +
							"</Print></Data>";
					Log.d("二维码", xml);
					try {
						String reslut = p.LabelPrint(getApplicationContext(), xml);
						Toast.makeText(getApplicationContext(), reslut, Toast.LENGTH_SHORT).show();
						p.Close();
					} catch (Exception ex) {
						p.Close();
						ex.getStackTrace();
					}
				} else {
					
					Intent printIntent = new Intent();   
					Bundle printBundle = new Bundle();
					printBundle.putSerializable("model", models);
					printBundle.putSerializable("attributeList", (Serializable)resAttributeList);
					printBundle.putSerializable("relationList", (Serializable)resRelationList);
					printIntent.putExtras(printBundle);
					try {
						printIntent.setComponent(new ComponentName("com.inspur.codeprint","com.inspur.codeprint.MainActivity"));   
						printIntent.setAction(Intent.ACTION_VIEW);   
						startActivity(printIntent);
					} catch (Exception e) {
						Toast.makeText(ResDetailActivity.this, "启动打印机失败！", Toast.LENGTH_SHORT).show();
						// TODO Auto-generated catch block
						e.printStackTrace();
					}   
					
				}
			}
			break;
			
		default:
			break;
		}
		return false;
	}
	
	/**
	 * 转向地图
	 * @param operFlag 0：GIS定位	 1：经纬度较准
	 */
	public void trans2Gis(int operFlag){
		String latitude = null;
		String longitude = null;
		String cityId = "";
		for(int i = 0; i < resAttributeList.size(); i++){
			ResAttr attr = resAttributeList.get(i);
			if(attr.getAttributeEnName().equalsIgnoreCase("latitude")){
				latitude = attr.getAttributeValue();
			}
			if(attr.getAttributeEnName().equalsIgnoreCase("longitude")){
				longitude = attr.getAttributeValue();
			}
			if(attr.getAttributeEnName().equalsIgnoreCase("city_id")){
				cityId = attr.getAttributeValue();
			}
		}
		
		if(latitude == null || longitude == null){
			Toast.makeText(ResDetailActivity.this, R.string.positon_not_found, Toast.LENGTH_SHORT).show();
		} else {
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putString("name", models.getName());
			bundle.putString("resclassenname", models.getResclassenname());
			bundle.putString("resclasscnname", models.getResclasscnname());
			bundle.putString("cityId", cityId);
			bundle.putString("latitude", latitude);
			bundle.putString("longitude", longitude);
			bundle.putString("useraccount", application.getUserInfo().getUseraccount());
			bundle.putString("intId", models.getInt_id());
			bundle.putString("serveraddress", URLManager.URL);
			bundle.putInt("operFlag", operFlag);
			intent.putExtras(bundle);
			try {
				intent.setComponent(new ComponentName("com.inspur.showmap","com.inspur.showmap.ShowMapActivity"));   
				startActivity(intent);
			} catch (Exception e) {
				Toast.makeText(ResDetailActivity.this, "请安装GIS查询应用！", Toast.LENGTH_SHORT).show();
				// TODO Auto-generated catch block
				e.printStackTrace();
			}   
		}
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == 10){
			resAttributeList.clear();
			resRelationList.clear();
			actionBar.removeAllTabs();
			this.queryDetailData();
		}
	}
	
	
	@Override
	protected void loadViewLayout() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processLogic() {
		// TODO Auto-generated method stub

	}
	public ResData getModels() {
		return models;
	}

	public void setModels(ResData models) {
		this.models = models;
	}
}
